package com.newbee.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.string;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.hhu.newbee.R;
import com.newbee.app.AppConfig;
import com.newbee.app.SpeechApp;
import com.newbee.http.ServerHttpUtil;
import com.newbee.listbean.NewMsgBean;
import com.newbee.listbean.NewMsgBean.MsgType;
import com.newbee.listbean.NewMsgBean.Status;
import com.newbee.round.CustomImageView;

public class NewMsgListAdapter extends BaseAdapter
{

	private Context context;
	private List<NewMsgBean> list;

	private static final int TYPE_QUNZU = 1;
	private static final int TYPE_FRINED = 2;

	private Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.arg1)
			{
			case TYPE_FRINED:
			{
				((TextView) msg.obj).setText("有来自<"
						+ msg.getData().get(USRNAME) + ">的好友请求！");
				break;
			}
			case TYPE_QUNZU:
			{
				((TextView) msg.obj).setText("有来自<"
						+ msg.getData().get(USRNAME) + ">的协同录音请求！");
				break;
			}

			default:
				break;
			}

		};
	};

	public static final String USRNAME = "USRNAME";

	public NewMsgListAdapter(Context context, List<NewMsgBean> list)
	{
		this.context = context;
		this.list = list;
	}

	@Override
	public int getCount()
	{
		if (list != null)
		{
			return list.size();
		}
		else
		{
			return 0;
		}

	}

	@Override
	public Object getItem(int arg0)
	{
		return arg0;
	}

	@Override
	public long getItemId(int arg0)
	{

		return arg0;
	}

	@Override
	public View getView(int p, View v, ViewGroup arg2)
	{
		final NewMsgBean bean = list.get(p);

		final ViewHolder viewHolder = new ViewHolder();
		if (v == null)
		{
			v = LayoutInflater.from(context).inflate(R.layout.listitem_msg,
					null);
		}

		viewHolder.headView = (CustomImageView) v.findViewById(R.id.msg_head);
		viewHolder.msgTypeTextView = (TextView) v.findViewById(R.id.msg_type);
		viewHolder.msgContentTextView = (TextView) v
				.findViewById(R.id.msg_content);
		viewHolder.msgStatusTextView = (TextView) v
				.findViewById(R.id.msg_status);
		// viewHolder.msgTimeTextView = (TextView)
		// v.findViewById(R.id.msg_time);

		int tempType = bean.getMsgtype();
		final String head = bean.getHead();
		final File file = new File(Environment.getExternalStorageDirectory()
				+ SpeechApp.HEAD_FILE + "/" + head + ".png");
		if (tempType == MsgType.FRIRND)
		{

			SoftReference<Bitmap> softReference = FriendsListvewAdapter.bitmapMap
					.get(head);
			if (softReference != null)
			{

				Bitmap bitmap = softReference.get();
				if (bitmap != null)
				{
					viewHolder.headView.setmSrc(bitmap);
					viewHolder.headView.postInvalidate();
				}
				else
				{

					if (file.exists())
					{

						try
						{
							FileInputStream fis = new FileInputStream(file);
							bitmap = BitmapFactory.decodeStream(fis);
							viewHolder.headView.setmSrc(bitmap);
							viewHolder.headView.postInvalidate();
							fis.close();

							FriendsListvewAdapter.bitmapMap.put(head,
									new SoftReference<Bitmap>(bitmap));
						}
						catch (FileNotFoundException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					else
					{
						new Thread(new Runnable()
						{

							public void run()
							{
								try
								{
									InputStream is = new URL(AppConfig.HTTP
											+ ServerHttpUtil.HEAD_dir + head
											+ ".png").openStream();

									Bitmap bitmap = BitmapFactory
											.decodeStream(is);
									is.close();
									viewHolder.headView.setmSrc(bitmap);
									viewHolder.headView.postInvalidate();
									FileOutputStream fis = new FileOutputStream(
											file);
									bitmap.compress(Bitmap.CompressFormat.PNG,
											100, fis);
									fis.close();
									FriendsListvewAdapter.bitmapMap.put(head,
											new SoftReference<Bitmap>(bitmap));
								}
								catch (FileNotFoundException e)
								{
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								catch (IOException e)
								{
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();

					}
				}

			}
			else
			{

				if (file.exists())
				{

					try
					{
						FileInputStream fis = new FileInputStream(file);
						Bitmap bitmap = BitmapFactory.decodeStream(fis);
						viewHolder.headView.setmSrc(bitmap);
						viewHolder.headView.postInvalidate();
						fis.close();

						FriendsListvewAdapter.bitmapMap.put(head,
								new SoftReference<Bitmap>(bitmap));
					}
					catch (FileNotFoundException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				else
				{
					new Thread(new Runnable()
					{

						public void run()
						{
							try
							{
								InputStream is = new URL(AppConfig.HTTP
										+ ServerHttpUtil.HEAD_dir + head
										+ ".png").openStream();

								Bitmap bitmap = BitmapFactory.decodeStream(is);
								is.close();
								viewHolder.headView.setmSrc(bitmap);
								viewHolder.headView.postInvalidate();
								FileOutputStream fis = new FileOutputStream(
										file);
								bitmap.compress(Bitmap.CompressFormat.PNG, 100,
										fis);
								fis.close();
								FriendsListvewAdapter.bitmapMap.put(head,
										new SoftReference<Bitmap>(bitmap));
							}
							catch (FileNotFoundException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							catch (IOException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}).start();

				}
			}

			viewHolder.msgTypeTextView.setText("好友添加请求");

			try
			{
				String strtemp = (String) SpeechApp.getUserNamePair().get(
						bean.getFromFriend().split("\\$")[0]);
				if (strtemp != null)
				{
					viewHolder.msgContentTextView.setText("有来自<" + strtemp
							+ ">的好友请求！");

				}
				else
				{
					new Thread()
					{
						@Override
						public void run()
						{

							String str = ServerHttpUtil.getUserName(bean
									.getFromFriend().split("\\$")[0]);

							try
							{
								JSONObject jo = new JSONObject(str);
								Iterator<Object> item = jo.keys();
								if (item.hasNext())
								{
									String key = item.next().toString();
									SpeechApp.setUserNamePair(key, jo.get(key)
											.toString());

									Message msg = new Message();
									msg.obj = viewHolder.msgContentTextView;
									Bundle bundle = new Bundle();
									bundle.putString(USRNAME, jo.get(key)
											.toString());
									msg.setData(bundle);
									msg.arg1 = TYPE_FRINED;
									handler.sendMessage(msg);

									//
								}
							}
							catch (JSONException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}.start();
				}

			}
			catch (JSONException e1)
			{
				new Thread()
				{
					@Override
					public void run()
					{

						String str = ServerHttpUtil.getUserName(bean
								.getFromFriend().split("\\$")[0]);

						try
						{
							JSONObject jo = new JSONObject(str);
							Iterator<Object> item = jo.keys();
							if (item.hasNext())
							{
								String key = item.next().toString();
								SpeechApp.setUserNamePair(key, jo.get(key)
										.toString());

								Message msg = new Message();
								msg.obj = viewHolder.msgContentTextView;
								Bundle bundle = new Bundle();
								bundle.putString(USRNAME, jo.get(key)
										.toString());
								msg.setData(bundle);
								msg.arg1 = TYPE_FRINED;
								handler.sendMessage(msg);

								//
							}
						}
						catch (JSONException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}.start();
				e1.printStackTrace();
			}

		}
		else
		{
			viewHolder.msgTypeTextView.setText("协同录音请求");

			viewHolder.headView.setmSrc(BitmapFactory.decodeResource(
					context.getResources(), R.drawable.msg_qunzu));

			viewHolder.headView.postInvalidate();
			try
			{
				String strtemp = (String) SpeechApp.getUserNamePair().get(
						bean.getRoom().split("\\$")[0]);
				if (strtemp != null)
				{
					viewHolder.msgContentTextView.setText("有来自<" + strtemp
							+ ">的协同录音请求！");

				}
				else
				{
					new Thread()
					{
						@Override
						public void run()
						{

							String str = ServerHttpUtil.getUserName(bean
									.getFromFriend().split("\\$")[0]);

							try
							{
								JSONObject jo = new JSONObject(str);
								Iterator<Object> item = jo.keys();
								if (item.hasNext())
								{
									String key = item.next().toString();
									SpeechApp.setUserNamePair(key, jo.get(key)
											.toString());

									Message msg = new Message();
									msg.obj = viewHolder.msgContentTextView;
									Bundle bundle = new Bundle();
									bundle.putString(USRNAME, jo.get(key)
											.toString());
									msg.setData(bundle);
									msg.arg1 = TYPE_QUNZU;
									handler.sendMessage(msg);
									// handler.handleMessage(msg);

									//
								}
							}
							catch (JSONException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}.start();
				}

			}
			catch (JSONException e1)
			{
				new Thread()
				{
					@Override
					public void run()
					{

						String str = ServerHttpUtil.getUserName(bean
								.getFromFriend().split("\\$")[0]);

						try
						{
							JSONObject jo = new JSONObject(str);
							Iterator<Object> item = jo.keys();
							if (item.hasNext())
							{
								String key = item.next().toString();
								SpeechApp.setUserNamePair(key, jo.get(key)
										.toString());

								Message msg = new Message();
								msg.obj = viewHolder.msgContentTextView;
								Bundle bundle = new Bundle();
								bundle.putString(USRNAME, jo.get(key)
										.toString());
								msg.setData(bundle);
								msg.arg1 = TYPE_QUNZU;
								handler.sendMessage(msg);

								//
							}
						}
						catch (JSONException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}.start();
				e1.printStackTrace();
			}
			// viewHolder.msgContentTextView.setText("有来自"
			// + bean.getRoom().split("\\$")[1] + "的协同录音请求！");

		}

		if (bean.getMsgStatus() == Status.SOLVE)
		{

			viewHolder.msgStatusTextView.setText("[已处理]");
		}
		else
		{

			viewHolder.msgStatusTextView.setText("[未处理]");
			// viewHolder.msgStatusTextView.setTextColor(0x2077d6);
			viewHolder.msgStatusTextView.setTextColor(context.getResources()
					.getColorStateList(R.color.steelblue));

		}

		// viewHolder.msgTimeTextView.setText(bean.getTime());
		// v.setTag(p + "");

		return v;

	}

	public List<NewMsgBean> getList()
	{
		return list;
	}

	public void setList(List<NewMsgBean> list)
	{
		this.list = list;
	}

	static class ViewHolder
	{

		CustomImageView headView;// 头像
		TextView msgTypeTextView;// 类型
		TextView msgContentTextView;// 展示时候小字的说明
		TextView msgStatusTextView;// 状态的说明
		TextView msgTimeTextView;// /时间的说明

	}

}
